package com.sale.plugins;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.SpringContextLoader;
import com.apache.exception.BusinessException;
import com.apache.funds.common.NumberUtil;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.UtilPlugin;
import com.apache.tools.DataMap;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SaleFinishActivityPluginImpl implements CustomMethodPlugin {

    private Logger log = Logger.getLogger(getClass());

    /**
     * @param param
     * @return
     */
    @SuppressWarnings("rawtypes")
    @Override
    public Object beforeInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        log.info("SaleFinishActivityPluginImpl=======>>>>>>>手动结束发行开始");
        Map<String, Object> map = new HashMap<String, Object>();
        //活动ID
        Object isFinish = param.get("isFinish");
        String saleId = (String) param.get("trsSale.w_saleId");
        //申购活动sale对象、申购总量、申购用户数、最小变动单位等
        DataMap saleMap = getSaleInfo(saleId);
        if (saleMap == null || saleMap.size() < 1) {
            throw new BusinessException("未找到发行活动");
        }
        //发行开始时间
        String startDate = (String) saleMap.get("saleDateStart");
        //发行结束时间
        String endDate = (String) saleMap.get("saleDateEnd");
        //发行数量netProxyManager
        String saleNum = (String) saleMap.get("saleNum");
        //发行成功比例
        String saleRatio = (String) saleMap.get("saleRatio");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("datasource",param.get("datasource"));
        //申购总数量
        String buyTotalNum = "0";
        //有申购人
        if ("T".equals(isFinish)) {
            // 未达到预设比例，更改活动状态，更改用户申购信息状态--》申购失败
            params.put("trsBuy.w_saleId", saleId);
            params.put("trsSale.w_saleId", saleId);
            params.put("trsSale.saleStatus", "41");//发行失败
            params.put("trsBuy.buyStatus", "50");//申购失败
            params.put("modelTypes", "u_trsBuy,u_trsSale");
            updateBuyInfo(params);
        }
        if ("N".equals(isFinish)) {
            //正常结束
            params.put("trsSale.w_saleId", saleId);
            params.put("trsSale.saleStatus", "40");//发行成功
            params.put("modelTypes", "u_trsSale");
            updateBuyInfo(params);
        }
        if (null == isFinish) {
            if (null != saleMap.get("buyTotalNum")) {
                buyTotalNum = saleMap.get("buyTotalNum") + "";
                //计算实际发售成功比例
                double realRatio = NumberUtil
                        .div(Double.parseDouble(buyTotalNum), Double.parseDouble(saleNum), 4) * 100;
                //实际发售比例是否大于预设比例
                if (realRatio < Double.parseDouble(saleRatio)) {
                    map.put("msg", "您的发售比例为：" + realRatio + "%，未达到预设发售比例，结束发行操作将视此次发行为发行失败。");
                    map.put("result", "F");
                    JSONObject fromObject = JSONObject.fromObject(map);
                    throw new BusinessException(fromObject.toString());
                } else {
                    map.put("msg", "您的发售比例为：" + realRatio + "%，已达到预设发售比例，结束发行操作将视此次发行为发行结束。");
                    map.put("result", "T");
                    JSONObject fromObject = JSONObject.fromObject(map);
                    throw new BusinessException(fromObject.toString());
                }
            } else {
                map.put("msg", "该发行活动还没有申购人。");
                map.put("result", "F");
                JSONObject fromObject = JSONObject.fromObject(map);
                throw new BusinessException(fromObject.toString());
            }
        }
        //判断当前日期是否已到发行结束时间
        //		String[] split = endDate.split("-");
        //		Date saleEndDate = DateUtil.getDate(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
        //		Date nowTime = new Date();
        //		//当前时间是否在发行结束时间之前
        //		boolean isNowBeforeEndTime = DateUtil.isStartBeforeEndTime(nowTime, saleEndDate);
        //		if(isNowBeforeEndTime){
        //
        //		}
        log.info("SaleFinishActivityPluginImpl=======>>>>>>>手动结束发行开始");
        return null;
    }

    @Override
    public Object doInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }

    /**
     * 综合查询：申购活动sale对象、申购总量、申购用户数等
     *
     * @param saleId
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public DataMap getSaleInfo(String saleId) {
        StringBuffer dyncSql = new StringBuffer("select s.*,");
        dyncSql.append("(select sum(t.num) from trs_buy t where t.sale_id='" + saleId
                + "')  as buy_total_num");//申购总数量
        dyncSql.append(" from trs_sale s where  s.sale_id='" + saleId + "'");
        log.info("手动结束发行，查询活动信息、申购总数SQL=>" + dyncSql);
        List<DataMap> list = (List<DataMap>)UtilPlugin.getInstance().selectObjectForDatasource(String.valueOf(dyncSql),"sale");
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 修改配号表信息，更新中签状态
     */
    @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
    public Object updateBuyInfo(Map<String, Object> buyMap) {
        ResultEntity dymicSqlParamResult = UtilPlugin.getInstance().saveByParams(String.valueOf(buyMap.get("datasource")),String.valueOf(buyMap.get("modelTypes")),buyMap);
        Map result = (Map) dymicSqlParamResult.getEntity();
        return null;
    }
}
